package jrmob.yonyou.com.commonlib.app_config_tool.tool.base;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Base64;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 描述:DrawableUtils 图片处理工具类
 * <p/>
 * Author: Zhangg
 * 日  期:  2016/7/9
 */
public class DrawableUtils {



    /**
     * base64转为bitmap
     * @param base64Data
     * @return
     */
    public static Bitmap base64ToBitmap(String base64Data) {
        byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    /**
     * bitmap转为base64
     * @param bitmap
     * @return
     */
    public static String bitmapToBase64(Bitmap bitmap) {

        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    /**
     * 转换图片成圆形
     * @param bitmap 传入Bitmap对象
     * @return
     */
    public static Bitmap toRoundBitmap(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float roundPx;
        float left,top,right,bottom,dst_left,dst_top,dst_right,dst_bottom;
        if (width <= height) {
            roundPx = width / 2;
            top = 0;
            bottom = width;
            left = 0;
            right = width;
            height = width;
            dst_left = 0;
            dst_top = 0;
            dst_right = width;
            dst_bottom = width;
        } else {
            roundPx = height / 2;
            float clip = (width - height) / 2;
            left = clip;
            right = width - clip;
            top = 0;
            bottom = height;
            width = height;
            dst_left = 0;
            dst_top = 0;
            dst_right = height;
            dst_bottom = height;
        }

        Bitmap output = Bitmap.createBitmap(width,
                height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect src = new Rect((int)left, (int)top, (int)right, (int)bottom);
        final Rect dst = new Rect((int)dst_left, (int)dst_top, (int)dst_right, (int)dst_bottom);
        final RectF rectF = new RectF(dst);

        paint.setAntiAlias(true);

        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, src, dst, paint);
        return output;
    }


    public static Bitmap imageZoom(Bitmap bitMap) {
//图片允许最大空间 单位：KB
        double maxSize = 200.00;
//将bitmap放至数组中，意在bitmap的大小（与实际读取的原文件要大）
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitMap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] b = baos.toByteArray();
//将字节换成KB
        double mid = b.length/1024;
//判断bitmap占用空间是否大于允许最大空间 如果大于则压缩 小于则不压缩
        if (mid > maxSize) {
//获取bitmap大小 是允许最大大小的多少倍
            double i = mid / maxSize;
//开始压缩 此处用到平方根 将宽带和高度压缩掉对应的平方根倍 （1.保持刻度和高度和原bitmap比率一致，压缩后也达到了最大大小占用空间的大小）
            bitMap = zoomImage(bitMap, bitMap.getWidth() / Math.sqrt(i),
                    bitMap.getHeight() / Math.sqrt(i));
        }
        return bitMap;
    }



    public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
                                   double newHeight) {
// 获取这个图片的宽和高
        float width = bgimage.getWidth();
        float height = bgimage.getHeight();
// 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();
// 计算宽高缩放率
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
// 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
                (int) height, matrix, true);
        return bitmap;
    }

    /** *
     *  功能: Bitmap - >  drawable
     *
     *  日 期: 2016/7/9
     */
    public static Drawable BitmapToDrawable(Bitmap bmp){
        Drawable drawable =new BitmapDrawable(bmp);
        return  drawable;

    }
    /** *
     *  功能: drawable - > Bitmap
     *
     *  日 期: 2016/7/9
     */
    public static Bitmap drawableToBitmap(Drawable drawable) {
        Bitmap bitmap = Bitmap.createBitmap(
                drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight(),
                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                        : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        //canvas.setBitmap(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }


    //将Bitmap处理为圆形的图片
    public static Bitmap circlePic(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int r = width < height ? width / 2 : height / 2; //圆的半径，取宽和高中较小的，以便于显示没有空白
        Bitmap outBitmap = Bitmap.createBitmap(r * 2, r * 2, Bitmap.Config.ARGB_8888); //创建一个刚好2r大小的Bitmap
        Canvas canvas = new Canvas(outBitmap); // 这里的这个Canvas就是我们用来绘制照片的Canvas
        final int color = 0xff424242;
        final Paint paint = new Paint();
        /**
         * 截取图像的中心的一个正方形,用于在原图中截取
         * 坐标如下：
         * 1.如果 w < h , 左上坐标(0, (h-w)/2) , 右上坐标(w, (h+w)/2)
         * 2.如果 w > h , 左上坐标((w-h)/2, 0) , 右上坐标((w+h)/2, h)
         */
        final Rect rect = new Rect(width < height ? 0 : (width - height) / 2, width < height ? (height - width) / 2 : 0,
                width < height ? width : (width + height) / 2, (width < height ? (height + width) / 2 : height));
        //创建一个直径大小的正方形，用于设置canvas的显示与设置画布截取
        final Rect rect2 = new Rect(0, 0, r * 2, r * 2);
        //提高精度，用于消除锯齿
        final RectF rectF = new RectF(rect2);
        //下面是设置画笔和canvas
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        //设置圆角，半径都为r,大小为rect2,这样绘制出来的就是一个圆形了
        canvas.drawRoundRect(rectF, r, r, paint);
        //设置图像重叠时的显示方式,这个设置很重要,设置了这个属性之后我们画照片进去就会以交集的形式截取,这样就会绘制出圆形的图片了
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        //绘制图像到canvas
        canvas.drawBitmap(bitmap, rect, rect2, paint);
        return outBitmap;
    }
}
